package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/*
全局过滤器，校验token是否有效
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 执行过滤的方法
     * @param exchange 交换机，可以获取请求和响应对象
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.判断是否是登录请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
                //localhost:51601/api/v1/login/login_auth
        URI uri = request.getURI();
        //获取请求路径  /api/v1/login/login_auth
        String path = request.getURI().getPath();
        if(path.contains("/login/login_auth")){
            //2.是，则放行
            return chain.filter(exchange);
        }

        //3.不是，则拦截
            //3.1 从请求头中获取token，是否有值
        String token = request.getHeaders().getFirst("token");
        //3.2 如果没有值，则拦截
        if(token==null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
            //3.3 如果有值，则判断是否有有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        //3.4 如果无效，则拦截
        if(i==1 || i==2){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
            //3.5 否则，放行
        return chain.filter(exchange);
    }

    /**
     * 过滤的执行的优先级，返回值越小优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
